package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送验证码
     *
     * @param phone   手机号
     * @param session session
     * @return Result
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //判断手机号是否符合格式
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(6);
        String key = RedisConstants.LOGIN_CODE_KEY + phone;
        //保存验证码到redis中设置验证码有效期
        stringRedisTemplate.opsForValue().set(key, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);


        //发送验证码
        log.debug("发送验证码成功，验证码:{}", code);
        return Result.ok();
    }

    /**
     * 登录功能
     *
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     * @param session   session
     * @return Result
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        //判断手机号是否符合格式
        if (RegexUtils.isPhoneInvalid(phone)) {
            log.error("手机号格式错误");
            return Result.fail("手机号格式错误");
        }
        String code = loginForm.getCode();

        //从redis中获取验证码并校验 去除空格
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        if (cacheCode == null || !code.equals(cacheCode.trim())) {
            return Result.fail("验证码错误");
        }

        // 根据手机号查询用户
        User user = query().eq("phone", phone).one();
        if (user == null) {
            //创建新用户并保存
            user = createUserWithPhone(phone);
        }
        // 保存用户到redis
        // 生成随机id
        String token = UUID.randomUUID().toString(true);

        // 将用户信息转换成map
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        // 忽略空值
                        .setIgnoreNullValue(true)
                        //转换字段名为String
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        //  保存用户信息到redis
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);

        // 设置token有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        // 返回token
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //  1. 获取当前用户
        Long userId = UserHolder.getUser().getId();

        //  2. 获取当天日期
        LocalDate now = LocalDate.now();

        //  3. 拼接key
        String key = USER_SIGN_KEY + userId + ":" + now.format(DateTimeFormatter.ofPattern("yyyyMM"));

        //  4. 获取今天是当月的第几天
        int day = now.getDayOfMonth();
        // 5. 写入redis
        stringRedisTemplate.opsForValue().setBit(key, day - 1, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //  1. 获取当前用户
        Long userId = UserHolder.getUser().getId();

        //  2. 获取当天日期
        LocalDate now = LocalDate.now();

        //  3. 拼接key
        String key = USER_SIGN_KEY + userId + ":" + now.format(DateTimeFormatter.ofPattern("yyyyMM"));

        //  4. 获取今天是当月的第几天
        int day = now.getDayOfMonth();

        // 5. 获取本月截止今天为止的所有的签到记录，返回的是一个十进制的数字 BITFIELD sign:5:202203 0 GET u14 0
        List<Long> num = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(day)
                ).valueAt(0));
        if (num == null || num.isEmpty()) {
            // 没有任何签到记录
            return Result.ok(0);
        }

        Long numOfSign = num.get(0);

        if (numOfSign == null || numOfSign == 0) {
            return Result.ok(0);
        }

        //6. num&1 计算连续签到次数
        int count = 0;
        while (true) {
            // 判断当前位是否为1
            if ((numOfSign & 1) == 0) {
                break;
            } else {
                count++;

                //  向右移一位
                numOfSign = numOfSign >> 1;
            }
        }
        return Result.ok(count);
    }

    /**
     * 创建新用户
     *
     * @param phone 手机号
     * @return User
     */
    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName("user_" + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
